'use client';

import { useState, useRef, useCallback } from 'react';
import { useASR } from '@/lib/hooks/useAI';

interface VoiceRecorderProps {
  onTranscription: (text: string) => void;
  disabled?: boolean;
  className?: string;
}

export function VoiceRecorder({ 
  onTranscription, 
  disabled = false, 
  className = "" 
}: VoiceRecorderProps) {
  const [isRecording, setIsRecording] = useState(false);
  const [recordingTime, setRecordingTime] = useState(0);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  
  const { speechToText, loading: asrLoading } = useASR();

  const startRecording = useCallback(async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);
      
      audioChunksRef.current = [];
      
      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunksRef.current.push(event.data);
        }
      };
      
      mediaRecorder.onstop = async () => {
        // Keep original recorded mime type (usually audio/webm;codecs=opus)
        const recordedType = audioChunksRef.current[0]?.type || 'audio/webm';
        const audioBlob = new Blob(audioChunksRef.current, { type: recordedType });
        
        // Convert to base64
        const reader = new FileReader();
        reader.onloadend = async () => {
          const base64Audio = reader.result as string;
          const base64Data = base64Audio.includes(',') ? base64Audio.split(',')[1] : base64Audio;
          
          try {
            const result = await speechToText({
              audioData: base64Data,
              language: 'en-US',
              mimeType: recordedType.includes('audio/') ? recordedType.split(';')[0] : 'audio/webm'
            });
            
            onTranscription(result.text);
          } catch (error) {
            console.error('Speech recognition failed:', error);
          }
        };
        reader.readAsDataURL(audioBlob);
        
        // Stop all audio tracks
        stream.getTracks().forEach(track => track.stop());
      };
      
      mediaRecorderRef.current = mediaRecorder;
      mediaRecorder.start();
      setIsRecording(true);
      setRecordingTime(0);
      
      // Start timing
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1);
      }, 1000);
      
    } catch (error) {
      console.error('Cannot access microphone:', error);
    }
  }, [speechToText, onTranscription]);

  const stopRecording = useCallback(() => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      setIsRecording(false);
      
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }
  }, [isRecording]);

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <button
        onClick={isRecording ? stopRecording : startRecording}
        disabled={disabled || asrLoading}
        className={`
          flex items-center justify-center w-10 h-10 rounded-full transition-all duration-200 shadow-sm
          ${isRecording 
            ? 'bg-red-500 hover:bg-red-600 text-white scale-105' 
            : 'bg-blue-500 hover:bg-blue-600 text-white hover:scale-105'
          }
          ${disabled || asrLoading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
        `}
        title={isRecording ? 'Stop Recording' : 'Start Recording'}
      >
        {asrLoading ? (
          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
        ) : isRecording ? (
          <div className="w-3 h-3 bg-white rounded-sm" />
        ) : (
          <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clipRule="evenodd" />
          </svg>
        )}
      </button>
      
      {isRecording && (
        <div className="flex items-center gap-2 text-sm text-gray-600">
          <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse" />
          <span className="font-medium">{formatTime(recordingTime)}</span>
        </div>
      )}
    </div>
  );
}